/**
 * capture.c
 */

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

#include <Base.h>

#include <capturer.h>

Capturer *findCapturer(Capturer *pList, char id) {
	Capturer *pCapturer = pList;
	while (pCapturer != NULL) {
		if (pCapturer->id == id) {
			break;
		}
		pCapturer = pCapturer->pNext;
	}

	return pCapturer;
}

Capturer *allocCapturer(char *pType, char *pBuff) {
	Capturer *pCapturer = (Capturer *) calloc(1, sizeof(Capturer));
	if (pCapturer != NULL) {
		pCapturer->id = pBuff[22];
		pCapturer->timeSeg = pBuff[23];
		if (pType != NULL) {
			*pType = pBuff[24];
		}
		pCapturer->pSchemeList = allocSchemeList(pBuff + 25);
	}
	
	return pCapturer;
}

void processCapturer(Capturer **ppList, Capturer *pProcCapturer) {
	Capturer *pCapturer = *ppList;
	Capturer *pNextCapturer;

	if (pCapturer == NULL) {
		*ppList = pProcCapturer;
		return;
	}

	while (pCapturer != NULL) {
		pNextCapturer = pCapturer->pNext;
		// find in head
 		if (pCapturer == *ppList && pCapturer->id == pProcCapturer->id) {
			freeCapturer(pCapturer);
			pProcCapturer->pNext = pNextCapturer;
			*ppList = pProcCapturer;
			break;
		}
		// find not in head
		if (pNextCapturer != NULL && pNextCapturer->id == pProcCapturer->id) {
			pCapturer->pNext = pProcCapturer;
			pProcCapturer->pNext = pNextCapturer->pNext;
			freeCapturer(pNextCapturer);
			break;
		}
		// not find
		if(pNextCapturer == NULL) {
			pCapturer->pNext = pProcCapturer;
			pProcCapturer->pNext = NULL;
			break;
		}

		pCapturer = pNextCapturer;
	}
}

int capturerToBuff(char *pBuff, int buffSize, Capturer *pCapturer) {
	int needSize = getSchemeListBuffSize(pCapturer->pSchemeList) + 25;
	LOGINFO("capturer need buffer size = %d   buffSize = %d \n", needSize, buffSize);
	
	if (needSize > buffSize) {
		LOGERROR("needSize > buffSize\n");
		return -1;
	}
	
	pBuff[22] = pCapturer->id;
	pBuff[23] = pCapturer->timeSeg;
	pBuff[24] = 3;
	schemeListToBuff(pBuff + 25, needSize - 25, pCapturer->pSchemeList);

	return needSize;
}

void printBuff(char *pTitle, char *pBuff, int size) {
	int i;
	printf("%s_BEGIN\n", pTitle);
	for (i = 0; i < size; i++) {
		printf("%02x ", pBuff[i]);
		if (i % 0x10 == 0xf) {
			printf("\n");
		}
	}
	printf("\n%s_END\n", pTitle);
}

